﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Windows.Forms;
using MES.DataGateway.SyncEntity;
using MES.DataGateway.Common;
using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncCommon;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.StandardEntity;
using System.IO;
using System.Configuration;
using System.Diagnostics;

namespace MES.DataGateway.StandardDataSync
{
    public class Product : SyncInfterface
    {
        private TreeView trvMes = new TreeView();
        private TreeView trvEnterprise = new TreeView();
        private List<OutInfoEntity> m_OutParameterObjectList = new List<OutInfoEntity>();
        private AssistantClass m_Assistant = new AssistantClass();
        private ServiceEntity m_ServiceInfoEntity = null;
        private OutInfoEntity m_OutParameterObject = null;
        private string m_ProjectID = "";
        private string m_LibID = "";
        private int m_CryNumber = 0;
        private string m_DataFilePath = "";
        private string m_StrDocumentName = "";
        private string m_AccessoriesPath = "";
        private string m_SyncType = "1";
        private string strProductName = "";
        private string strVersion = "";
        private string m_camstarpathtemp = ConfigurationManager.AppSettings["CamstarPathTemp"].Trim();
        private string m_FileName = "";//add:Wangjh 2017-9-15
        private StandardDAL m_dal = new StandardDAL();
        private XmlDocument m_myXml;//add:Wangjh 20220901
        private const string m_gzPlant = "604";//工装工具分公司的分厂代码 add:wangjh 20241203
        private string m_ProcessPlant = "";//工艺车间 add:wangjh 20241203

        #region 属性
        public string SyncType
        {
            get { return m_SyncType; }
            set { m_SyncType = value; }
        }

        public OutInfoEntity OutParameterObject
        {
            get { return m_OutParameterObject; }
        }

        public List<OutInfoEntity> OutParameterObjectList
        {
            get { return m_OutParameterObjectList; }
        }

        public string AccessoriesPath
        {
            set { m_AccessoriesPath = value; }
        }

        public ServiceEntity ServiceInfoEntity
        {
            get { return m_ServiceInfoEntity; }
            set { m_ServiceInfoEntity = value; }
        }

        public string ProjectID
        {
            get { return m_ProjectID; }
            set { m_ProjectID = value; }
        }

        public string LibID
        {
            get { return m_LibID; }
            set { m_LibID = value; }
        }

        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }
        #endregion

        #region 获取循环节点的循环次数
        private void GetCryNodeNumber(string nodeFullPath)
        {
            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (node.FullPath == nodeFullPath)
                {
                    m_CryNumber = m_CryNumber + 1;
                }
                else
                {
                    GetCryChidlNodeNumber(nodeFullPath, node);
                }
            }
        }

        private void GetCryChidlNodeNumber(string nodeFullPath, TreeNode childNodes)
        {
            foreach (TreeNode node in childNodes.Nodes)
            {
                if (node.FullPath == nodeFullPath)
                {
                    m_CryNumber = m_CryNumber + 1;
                }
                else
                {
                    GetCryChidlNodeNumber(nodeFullPath, node);
                }
            }
        }
        #endregion

        #region 根据映射条件查找对应的值
        private string SearchMappingValue(string nodeFullPath)
        {
            string strRturnValue = "";
            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (node.FullPath.ToLower() == nodeFullPath.ToLower())
                {
                    if (node.Tag == null)
                    {
                        strRturnValue = "";
                        break;
                    }
                    else
                    {
                        strRturnValue = node.Tag.ToString().Trim();
                        break;
                    }
                }
                else
                {
                    strRturnValue = SearchChildMappingValue(nodeFullPath, node);
                    if (strRturnValue.Trim() != "") //todo litan 20150507
                    {
                        break;
                    }
                }
            }
            return strRturnValue;
        }

        private string SearchChildMappingValue(string nodeFullPath, TreeNode childNodes)
        {
            string strRturnValue = "";
            foreach (TreeNode node in childNodes.Nodes)
            {
                if (node.FullPath.ToLower() == nodeFullPath.ToLower()) //todo litan 20150507
                {
                    if (node.Tag == null)
                    {
                        strRturnValue = "";
                        break;
                    }
                    else
                    {
                        strRturnValue = node.Tag.ToString().Trim();
                        break;
                    }
                }
                else
                {
                    strRturnValue = SearchChildMappingValue(nodeFullPath, node);
                    if (strRturnValue.Trim() != "")
                    {
                        break;
                    }
                }
            }
            return strRturnValue;
        }
        #endregion

        #region 循环取相关节点值
        private string GetCryValue(string resourceFullPath, int intIndex)
        {
            string strReturnValue = "";
            List<string> valueList = new List<string>();

            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (node.FullPath == resourceFullPath)
                {
                    string strNodeValue = "";
                    if (node.Tag != null)
                    {
                        strNodeValue = node.Tag.ToString().Trim();
                    }
                    valueList.Add(strNodeValue);
                }
                else
                {
                    GetChildCryValue(resourceFullPath, node, valueList);
                }
            }

            for (int i = 0; i < valueList.Count; i++)
            {
                if (i == intIndex)
                {
                    strReturnValue = valueList[i];
                    break;
                }
            }
            return strReturnValue;
        }

        private void GetChildCryValue(string resourceFullPath, TreeNode parentNode, List<string> valueList)
        {
            foreach (TreeNode node in parentNode.Nodes)
            {
                if (node.FullPath == resourceFullPath)
                {
                    string strNodeValue = "";
                    if (node.Tag != null)
                    {
                        strNodeValue = node.Tag.ToString().Trim();
                    }
                    valueList.Add(strNodeValue);
                }
                else
                {
                    GetChildCryValue(resourceFullPath, node, valueList);
                }
            }
        }
        #endregion

        #region 导入数据文件
        private void LoadXmlData()
        {
            string strFilter = string.Format("ProjectID='{0}' and libID='{1}'", m_ServiceInfoEntity.ProjectID, m_LibID);
            DataRow[] rows = m_ServiceInfoEntity.ServiceTable.Select(strFilter);

            CreateMesTemple(Application.StartupPath + "\\XML\\Template\\MES\\" + rows[0]["MesTemplate"].ToString().Trim());
            LoadEnterpriseXML(m_DataFilePath);
        }

        private void LoadEnterpriseXML(string strPath)
        {
            m_FileName = Path.GetFileName(strPath);//add:Wangjh 2017-9-15
            trvEnterprise.Nodes.Clear();
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strPath);

            XmlNode stu = myxml.DocumentElement;
            foreach (XmlNode node in stu.ChildNodes)
            {
                TreeNode childNodes = new TreeNode();
                childNodes.Text = node.Name;
                childNodes.Name = childNodes.Text;
                childNodes.Tag = node.InnerText;
                GetChildXmlNode(node, childNodes);
                trvEnterprise.Nodes.Add(childNodes);
            }
        }

        private void GetChildXmlNode(XmlNode nodes, TreeNode childTreeNode)
        {
            if (nodes.ChildNodes.Count == 0)
            {
                return;
            }
            else
            {
                foreach (XmlNode childNode in nodes.ChildNodes)
                {
                    TreeNode myNode = new TreeNode();
                    myNode.Text = childNode.Name;
                    myNode.Name = myNode.Text;
                    myNode.Tag = childNode.InnerText;
                    GetChildXmlNode(childNode, myNode);
                    childTreeNode.Nodes.Add(myNode);
                }
            }
        }

        private void CreateMesTemple(string strFileName)
        {
            trvMes.Nodes.Clear();
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strFileName);
            if (myxml.DocumentElement == null)
            {
                return;
            }
            XmlNode stu = myxml.DocumentElement;
            foreach (XmlNode node in stu.ChildNodes)
            {
                TreeNode childNodes = new TreeNode();
                childNodes.Text = node.Name;
                if (node.Attributes.GetNamedItem("Type") != null)
                {
                    childNodes.Tag = node.Attributes.GetNamedItem("Type").Value;
                }
                else
                {
                    childNodes.Tag = "";
                }
                GetMesChildXmlNode(node, childNodes);
                trvMes.Nodes.Add(childNodes);
            }
        }

        private void GetMesChildXmlNode(XmlNode nodes, TreeNode childTreeNode)
        {
            if (nodes.ChildNodes.Count == 0)
            {
                return;
            }
            else
            {
                foreach (XmlNode childNode in nodes.ChildNodes)
                {
                    TreeNode myNode = new TreeNode();
                    myNode.Text = childNode.Name;
                    if (childNode.Attributes.GetNamedItem("Type") != null)
                    {
                        myNode.Tag = childNode.Attributes.GetNamedItem("Type").Value;
                    }
                    else
                    {
                        myNode.Tag = "";
                    }
                    GetMesChildXmlNode(childNode, myNode);
                    childTreeNode.Nodes.Add(myNode);
                }
            }
        }
        #endregion

        #region 查找单节点映射值
        private string GetMappingValue(TreeNode node)
        {
            string strValue = "";
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ProjectID, m_LibID, node.FullPath);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记
            if (mappingRows.Length > 0)
            {//多个映射，多次获取直到取到值 yangsj 20180327
                for (int i = 0; i <= mappingRows.Length - 1; i++)
                {
                    strValue = SearchMappingValue(mappingRows[i]["EnterpriseFileld"].ToString().Trim());
                    if (!string.IsNullOrWhiteSpace(strValue.Trim()))
                        break;
                }
            }
            return strValue;
        }
        #endregion

        #region 查找目标文件映射路径
        private string GetMappingPath(TreeNode node)
        {
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ProjectID, m_LibID, node.FullPath);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记
            if (mappingRows.Length > 0)
            {
                return mappingRows[0]["EnterpriseFileld"].ToString().Trim();
            }
            else
            {
                return "";
            }
        }
        #endregion

        private void GetProductData(ref SyncParameterEntity mainEntity, ref string strDZJ)
        {
            mainEntity.OperationKind = "New";
            mainEntity.ServiceKey = "Product";
            mainEntity.DataList = new List<DataEntity>();
            string strMaterialMark = "";
            string strMaterialSpecification = "";

            GetMaterialValue(ref strMaterialMark, ref strMaterialSpecification, ref strDZJ);
            GetROUGH(mainEntity);
            //如果是压气机叶片分厂，锻件的话需要记录第一次使用的零件（FirstUsedProduct）值  add:Wangjh 20211014
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            var factory = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2plant");
            if (factory != null && factory.InnerText == "608")
            {
                var FirstUsedProduct = myxml.SelectSingleNode("/Root/product/item/ly2part_no");
                if (FirstUsedProduct != null && !string.IsNullOrWhiteSpace(FirstUsedProduct.InnerText))
                {
                    DataEntity entity = new DataEntity();
                    entity.FieldName = "FirstUsedProduct";
                    entity.FieldType = "dataField";
                    entity.FieldValue = FirstUsedProduct.InnerText;
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);
                }
            }
            //
            foreach (TreeNode node in trvMes.Nodes)
            {
                //if (node.Text != "Product") //todo ltian 20150507
                //    continue;
                foreach (TreeNode wChildNode in node.Nodes) //workFlow下面业务数据处理
                {
                    if (wChildNode.Text == "Documentset")
                    {
                        if (m_StrDocumentName.Trim() == "")
                        {
                            continue;
                        }
                        DataEntity entity = new DataEntity();
                        entity.FieldName = "DocumentSet";
                        entity.FieldType = "namedObjectField";
                        entity.FieldValue = m_StrDocumentName;
                        entity.FileldVersion = "";
                        mainEntity.DataList.Add(entity);
                    }
                    else if (wChildNode.Text == "ProductType")
                    {
                        string strValue = GetMappingValue(wChildNode);
                        if (strValue.Trim() == "")
                        {
                            string strProductType = GetProductType();

                            DataEntity entity = new DataEntity();
                            entity.FieldName = "ProductType";
                            entity.FieldType = "namedObjectField";
                            entity.FieldValue = strProductType;
                            entity.FileldVersion = "";
                            mainEntity.DataList.Add(entity);
                        }
                        else
                        {
                            DataEntity entity = new DataEntity();
                            entity.FieldName = wChildNode.Text;
                            entity.FieldType = wChildNode.Tag.ToString().Trim();
                            entity.FieldValue = strValue;
                            entity.FileldVersion = "";
                            mainEntity.DataList.Add(entity);
                        }
                    }
                    //else if (m_ProcessPlant == m_gzPlant && wChildNode.Text == "MaterialSize")//工装工具分公司特殊处理，此字段作为毛料数量用 add:wangjh 20241203
                    //{
                    //    try
                    //    {
                    //        DataEntity entity = new DataEntity();
                    //        entity.FieldName = wChildNode.Text;
                    //        entity.FieldType = wChildNode.Tag.ToString().Trim();
                    //        entity.FieldValue = m_myXml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2mlsl").InnerText;
                    //        entity.FileldVersion = "";
                    //        mainEntity.DataList.Add(entity);
                    //    }catch(Exception ex){};
                    //}
                    else
                    {
                        if (wChildNode.Tag.ToString().Trim() == "dataField" || wChildNode.Tag.ToString().Trim() == "namedObjectField")
                        {
                            #region 赋值

                            string strValue = "";
                            if (wChildNode.Text == "Name")
                            {
                                strValue = strProductName;
                            }
                            else if (wChildNode.Text == "Revision")
                                strValue = strVersion;
                            else
                                strValue = GetMappingValue(wChildNode);
                            //目前逻辑:如果毛料工序上没有材料牌号等信息,则从工艺上取.20190419:更改为不从工艺上取了 by:Wangjh
                            if (wChildNode.Text == "MaterialSpecification")//零件材料牌号，规格取值 
                                //strValue = string.IsNullOrWhiteSpace(strMaterialSpecification) ? strValue : strMaterialSpecification;
                                strValue = strMaterialSpecification;
                            else if (wChildNode.Text == "MaterialTrademark")//零件材料牌号，规格取值
                                //strValue = string.IsNullOrWhiteSpace(strMaterialMark) ? strValue : strMaterialMark;
                                strValue = strMaterialMark;
                            if (strValue.Trim() != "")
                            {
                                DataEntity entity = new DataEntity();
                                entity.FieldName = wChildNode.Text;
                                entity.FieldType = wChildNode.Tag.ToString().Trim();
                                entity.FieldValue = strValue;
                                entity.FileldVersion = "";
                                mainEntity.DataList.Add(entity);
                            }
                            #endregion
                        }
                        else if (wChildNode.Tag.ToString().Trim() == "revisionedObjectField")
                        {
                            #region 赋值
                            foreach (TreeNode childNode in wChildNode.Nodes)
                            {
                                string strName = "";
                                string strVersion = "1";
                                if (childNode.Text == "Name")
                                {
                                    string strValue = GetMappingValue(childNode);
                                    strName = strValue;
                                }
                                else if (childNode.Text == "Revision")
                                {
                                    string strValue = GetMappingValue(childNode);
                                    if (strValue.Trim() != "")
                                    {
                                        strVersion = strValue;
                                    }
                                }
                                if (strName.Trim() != "")
                                {
                                    DataEntity entity = new DataEntity();
                                    entity.FieldName = wChildNode.Text;
                                    entity.FieldType = wChildNode.Tag.ToString().Trim();
                                    entity.FieldValue = strName;
                                    entity.FileldVersion = strVersion;
                                    mainEntity.DataList.Add(entity);
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 零件材料牌号，规格取值
        /// </summary>
        /// <param name="attName"></param>
        /// <returns></returns>
        private void GetMaterialValue(ref string strMaterialMark, ref string strMaterialSpecification, ref string strDZJ)
        {
            //XmlDocument myxml = new XmlDocument();
            //myxml.Load(m_DataFilePath);
            //获取件号信息
            XmlNode stu = m_myXml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "MEOP")
                    continue;
                if (node.ChildNodes.Count == 0)
                    continue;
                XmlNode nodeCheck = node.SelectSingleNode("MeopType");
                if (nodeCheck.InnerText.Trim() != "毛料工序")
                    continue;
                XmlNode _node = node.SelectSingleNode("ly2material_mark");
                if (_node != null)
                    strMaterialMark = _node.InnerText.Trim();
                _node = node.SelectSingleNode("ly2blank_spec");
                if (_node != null)
                    strMaterialSpecification = _node.InnerText.Trim();
                _node = node.SelectSingleNode("ly2rough_quantity");
                if (_node != null)
                {
                    strDZJ = _node.InnerText.Trim();
                    if (strDZJ == "锻铸件")
                        strDZJ = "是";
                    else
                        strDZJ = "否";
                }
            }
            //获取管批工艺的材料牌号和规格 add:Wangjh 20190321
            XmlNodeList GPNode = stu.SelectNodes("/Root/product/item/CLGG");
            if (GPNode.Count > 0) { strMaterialSpecification = GPNode[0].InnerText; }//材料规格
            GPNode = stu.SelectNodes("/Root/product/item/CLPH");
            if (GPNode.Count > 0) { strMaterialMark = GPNode[0].InnerText; }//材料牌号
            //

            //工装工具分公司的材料牌号和规格从工艺上取 add:wangjh 20241203
            if (m_ProcessPlant == m_gzPlant) {
                try
                {
                    strMaterialSpecification = m_myXml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2blank_spec").InnerText;
                    strMaterialMark = m_myXml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2material_mark").InnerText;
                }catch(Exception ex){}
            }

            m_Assistant.ReplaceProductH(m_myXml, ref strProductName);
        }
        /// <summary>
        /// 管理管件毛坯
        /// </summary>
        /// <param name="mainEntity"></param>
        private void GetROUGH(SyncParameterEntity mainEntity)
        {
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            //获取件号信息
            XmlNode stu = myxml.SelectSingleNode("/Root/ROUGH");
            if (stu == null || stu.ChildNodes.Count == 0)//add:Wangjh 20180919  stu.ChildNodes .Count ==0
                return;
            string strmaterialtype = stu.SelectSingleNode("ly2rough_type").InnerText;
            DataEntity entity = new DataEntity("MaterialType", "namedObjectField", strmaterialtype, "");
            mainEntity.DataList.Add(entity);

            string strmaterialname = stu.SelectSingleNode("ly2rough_no").InnerText;
            entity = new DataEntity("MaterialRequest", "dataField", strmaterialname, "");
            mainEntity.DataList.Add(entity);
        }

        private string GetProductType()
        {
            string typeValue = GetCryValue("product\\item\\ae8_isStandard", 0);//是否标准件
            if (typeValue == "Y")
            {
                return "标准件";
            }

            typeValue = GetCryValue("product\\item\\ae8_isSelfDesign", 0);//是否自制件
            if (typeValue == "Y")
            {
                return "自制件";
            }

            typeValue = GetCryValue("product\\item\\ae8_isUniversal", 0);//是否通用件
            if (typeValue == "Y")
            {
                return "通用件";
            }
            typeValue = GetCryValue("product\\item\\ae8_isPurchase", 0);//是否成附件

            if (typeValue == "Y")
            {
                return "成附件";
            }
            return ConfigurationManager.AppSettings["ProductType"];
        }



        //检查是否有productfamile 没有则添加
        private void ProcessPorudctFamily(string strProductFamily)
        {
            StandardDAL dal = new StandardDAL();
            DataSet ds = dal.GetProductFamily(strProductFamily);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return;
            }
            else
            {
                OutInfoEntity infoEntity = new OutInfoEntity();
                ExecuteAPI exectAPI = new ExecuteAPI();
                exectAPI.CreateNDOData("ProductFamily", strProductFamily, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 2)//add:Wangjh 2017-9-15 
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "ProductFamily创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
                else
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库  
                }
            }
        }

        private void ProcessNDOEntity(string strTable, string strName, string strValue)
        {
            StandardDAL dal = new StandardDAL();
            DataSet ds = dal.GetNDOTable(strTable, strName, strValue);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                return;
            }
            else
            {
                OutInfoEntity infoEntity = new OutInfoEntity();
                ExecuteAPI exectAPI = new ExecuteAPI();
                exectAPI.CreateNDOData(strTable, strValue, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 2)//add:Wangjh 2017-9-15 
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strTable + "创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
                else
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strTable + "创建成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
            }
        }

        public void Execute()
        {
            m_Assistant.DataFilePath = m_DataFilePath;
            Log.SetConfig();//add:Wangjh 2017-9-15 
            LoadXmlData();

            List<string> FilesNameList = new List<string>();
            strProductName = strVersion = "";

            m_myXml = new XmlDocument();
            m_myXml.Load(m_DataFilePath);
            m_ProcessPlant= m_myXml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2plant").InnerText; 


            #region Service类别判断
            TreeNode[] e_nodes = trvEnterprise.Nodes.Find("Service", false);
            if (e_nodes.Length == 0)
                return;

            if (m_SyncType == "1")
            {
                if (e_nodes[0].Tag.ToString().Trim() == "")
                {
                    return;
                }
                //else if (e_nodes[0].Tag.ToString().Trim() != "Product") //todo 20150507
                //{
                //    return;
                //}
            }
            #endregion

            foreach (TreeNode M_node in trvMes.Nodes)
            {
                if (M_node.Text != "Product") //todo 20150507
                    continue;
                foreach (TreeNode wChildNode in M_node.Nodes) //业务数据处理
                {
                    if (wChildNode.Text == "Name")
                    {
                        strProductName = GetMappingValue(wChildNode);
                    }
                    else if (wChildNode.Text == "Revision")
                    {
                        string strValue = GetMappingValue(wChildNode);
                        if (strValue.Trim() == "")
                        {
                            strVersion = "1";
                        }
                        else
                        {
                            strVersion = strValue;
                        }
                    }
                    else if (wChildNode.Text == "Documentset")
                    {
                        foreach (TreeNode item in trvEnterprise.Nodes[3].Nodes)
                        {
                            GetDocumentList(FilesNameList, item);
                        }
                    }
                }
            }
            Log.WriteLog("开始处理product:" + strProductName, 1, m_DataFilePath);
            //  LoadDocumentSet(FilesNameList);
            LoadDocumentNew(FilesNameList);

            LoadProduct();
            LoadUrls();
        }

        private void LoadProduct()
        {
            StandardDAL dal = new StandardDAL();
            if (strProductName.Trim() == "")
            {
                Log.WriteLog("没有零件图号，无法导入数据", 1, "product数据导入,数据文件" + m_DataFilePath);
                Log.WriteOrcale("PDMTOMES_Product" + "@^" + "没有零件图号，无法导入数据" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库      
                return;
            }
            ExecuteAPI exectAPI = new ExecuteAPI();
            SyncParameterEntity productEntity = new SyncParameterEntity();
            string strDZJ = "";
            GetProductData(ref productEntity, ref strDZJ);

            if (strProductName.Substring(0, 2) == "XN")
            {
                productEntity.DataList.Add(new DataEntity("IsPhantom", "dataField", 1, ""));
            }

            foreach (DataEntity tmpEntity in productEntity.DataList)
            {
                if (tmpEntity.FieldType != "namedObjectField")
                {
                    continue;
                }
                //处理producttype和productfamily
                else if (tmpEntity.FieldName == "ProductFamily")
                { ProcessPorudctFamily(tmpEntity.FieldValue.ToString().Trim()); }
                else
                {
                    ProcessNDOEntity(tmpEntity.FieldName, tmpEntity.FieldName + "name", tmpEntity.FieldValue.ToString().Trim());
                }
            }

            Dictionary<string, Dictionary<string, List<DataEntity>>> subentityList = null;
            if (!string.IsNullOrWhiteSpace(strDZJ))
            {
                subentityList = new Dictionary<string, Dictionary<string, List<DataEntity>>>();
                //增加锻铸件类型保存
                Dictionary<string, List<DataEntity>> AttributesList = new Dictionary<string, List<DataEntity>>();
                List<DataEntity> AttributesItem = new List<DataEntity>();
                AttributesItem.Add(new DataEntity("Name", "dataField", "锻铸件类型", ""));
                AttributesItem.Add(new DataEntity("AttributeValue", "dataField", strDZJ, ""));
                AttributesItem.Add(new DataEntity("IsExpression", "dataField", "False", ""));
                AttributesItem.Add(new DataEntity("DataType", "dataField", 4, ""));
                AttributesList.Add("0", AttributesItem);
                subentityList.Add("Attributes", AttributesList);
            }

            DataTable productdt = dal.GetRDOByAllVersion("Product", "ProductName", strProductName);

            OutInfoEntity infoEntity = new OutInfoEntity();
                       

            if (productdt.Rows.Count > 0)
            {

                if (productdt.Select(string.Format("ProductName='{0}' and ProductRevision='{1}'", strProductName, strVersion)).Length == 0)
                {
                    string strVer = productdt.Select("ProductID=Revofrcdid")[0]["ProductRevision"].ToString();

                    exectAPI.CreateRDOEntityRevision("Product", strProductName, strVer, productEntity, subentityList, ref infoEntity);



                    m_OutParameterObjectList.Add(infoEntity);
                    if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                    {
                        Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }
                    else if (infoEntity.OutFlag == 2)
                    {
                        Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + "Product新版本创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }
                }
                else
                {
                    //获取现有属性
                    string id = productdt.Select(string.Format("productrevision='{0}'", strVersion))[0]["productid"].ToString();
                    DataTable userAtributeDt = dal.GetNDOTable("Userattribute", "Parentid", id).Tables[0];
                    //

                    exectAPI.UpdateRDOEntity("Product", strProductName, strVersion, productEntity, subentityList, userAtributeDt.Rows.Count, ref infoEntity);


                    m_OutParameterObjectList.Add(infoEntity);
                    if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                    {
                        Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }
                    else if (infoEntity.OutFlag == 2)
                    {
                        Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + "Product修改失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }

                }

                #region"叶片分厂的锻件erp给订单时按materialcode作为name复制了一份product，此时更新复制的那一份也要更新 add:Wangjh 20211014"
                //叶片分厂的锻件erp给订单时按materialcode作为name复制了一份product，此时更新复制的那一份也要更新 add:Wangjh 20211014
                XmlDocument myxml = new XmlDocument();
                myxml.Load(m_DataFilePath);
                var factory = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2plant");
                DataTable MDJDt = new DataTable();
                //if (factory != null && factory.InnerText == "608")
                //{
                    MDJDt = dal.GetMDJERPProduct(strProductName);
                    if (MDJDt.Rows.Count > 0)
                    {
                        var productEntity2 = new SyncParameterEntity()
                        {
                            ServiceKey = productEntity.ServiceKey,
                            OperationKind = productEntity.OperationKind,
                            DataList = productEntity.DataList,
                            MainParameterName = productEntity.MainParameterName,
                            MainParameterVersion = productEntity.MainParameterVersion
                        };


                        //替换productName和materialcode
                        foreach (var data in productEntity2.DataList)
                        {
                            if (data.FieldName == "Name")
                            {
                                data.FieldValue = MDJDt.Rows[0]["productname"].ToString();
                            }
                            if (data.FieldName == "MaterialCode")
                            {
                                data.FieldValue = strProductName;
                            }
                            if (data.FieldName == "ProductType") {
                                data.FieldValue = "叶片锻件虚拟件";
                            }
                        }

                        if (MDJDt.Select("productrevision='" + strVersion + "'").Length == 0)
                        {
                            string strVer = MDJDt.Select("ProductID=Revofrcdid")[0]["ProductRevision"].ToString();

                            exectAPI.CreateRDOEntityRevision("Product", MDJDt.Rows[0]["productname"].ToString(), strVer, productEntity2, subentityList, ref infoEntity);

                        }
                        else
                        {
                            //获取现有属性
                            string id = MDJDt.Select(string.Format("productrevision='{0}'", strVersion))[0]["productid"].ToString();
                            DataTable userAtributeDt = dal.GetNDOTable("Userattribute", "Parentid", id).Tables[0];
                            //
                            exectAPI.UpdateRDOEntity("Product", MDJDt.Rows[0]["productname"].ToString(), strVersion, productEntity2, subentityList, userAtributeDt.Rows.Count, ref infoEntity);

                        }

                    }
                //}
                
                #endregion

                #region "所有相关的子件号也得更新"
                DataTable subProduct = m_dal.GetSubProduct(strProductName, strVersion);
                if (subProduct.Rows.Count > 0)
                {
                    var productEntity3 = new SyncParameterEntity()
                    {
                        ServiceKey = productEntity.ServiceKey,
                        OperationKind = productEntity.OperationKind,
                        DataList = productEntity.DataList,
                        MainParameterName = productEntity.MainParameterName,
                        MainParameterVersion = productEntity.MainParameterVersion
                    };

                    foreach (DataRow dr in subProduct.Rows)
                    {
                        foreach (var data in productEntity3.DataList)
                        {
                            if (data.FieldName == "Name")
                            {
                                data.FieldValue =dr["productname"].ToString();
                            }
                            if (data.FieldName == "ProductType")
                            {
                                data.FieldValue = dr["producttypename"].ToString();
                            } 
                        }
                        exectAPI.UpdateRDOEntity("Product", dr["productname"].ToString(), dr["productrevision"].ToString(), productEntity3, subentityList, int.Parse(dr["AttributeCount"].ToString()), ref infoEntity);
                    }
                }

                #endregion
            }
            else
            {
                exectAPI.CreateRDOEntity("Product", productEntity, subentityList, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
                else if (infoEntity.OutFlag == 2)
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strProductName + ":" + strVersion + "," + "Product创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
            }

        }

        private void LoadDocumentSet(List<string> FilesNameList)
        {
            try
            {
                StandardDAL dal = new StandardDAL();
                string DocumentSetName = "";
                if (FilesNameList.Count == 0)
                {
                    return;
                }
                //文档集名称
                DocumentSetName = string.Format("{0}-{1}-{2}", strProductName, strVersion, DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                Dictionary<string, string> NameAndRev = new Dictionary<string, string>();
                ExecuteAPI exectAPI = new ExecuteAPI();
                OutInfoEntity infoEntity;
                OutInfoEntity info1Entity;

                for (int k = 0; k < FilesNameList.Count; k++)
                {
                    if (!File.Exists(m_AccessoriesPath + "\\" + FilesNameList[k]))
                    {
                        Log.WriteLog("未找到文件", 0, FilesNameList[k] + "未找到,跳过处理！");
                        Log.WriteOrcale("PDMTOMES_ProductDocument" + "@^" + "未找到文件" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                        continue;
                    }
                    m_StrDocumentName = string.Format("{0}-{1}", Path.GetFileNameWithoutExtension(FilesNameList[k]), DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                    #region 赋值document
                    SyncParameterEntity mainEntity = new SyncParameterEntity();

                    mainEntity.OperationKind = "New";
                    mainEntity.ServiceKey = "Document";
                    mainEntity.DataList = new List<DataEntity>();

                    DataEntity entity = new DataEntity();
                    entity.FieldName = "Name";
                    entity.FieldType = "dataField";
                    entity.FieldValue = m_StrDocumentName;
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "Notes";
                    entity.FieldType = "dataField";
                    entity.FieldValue = FilesNameList[k];
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "Revision";
                    entity.FieldType = "dataField";
                    entity.FieldValue = "1";
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    string strAA = m_Assistant.uniqName();
                    string strTmp1 = m_camstarpathtemp + strAA;

                    if (!Directory.Exists(strTmp1))
                        Directory.CreateDirectory(strTmp1);

                    File.Move(m_AccessoriesPath + "\\" + FilesNameList[k], strTmp1 + "\\" + FilesNameList[k]);

                    entity = new DataEntity();
                    entity.FieldName = "Identifier";
                    entity.FieldType = "dataField";
                    entity.FieldValue = strTmp1 + "\\" + FilesNameList[k];
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "FileLocation";
                    entity.FieldType = "dataField";
                    entity.FieldValue = strTmp1;
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "Status";
                    entity.FieldType = "dataField";
                    entity.FieldValue = "1";
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "FileName";
                    entity.FieldType = "dataField";
                    entity.FieldValue = FilesNameList[k];
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);

                    entity = new DataEntity();
                    entity.FieldName = "UploadFile";
                    entity.FieldType = "dataField";
                    entity.FieldValue = "true";
                    entity.FileldVersion = "";
                    mainEntity.DataList.Add(entity);
                    #endregion

                    infoEntity = new OutInfoEntity();
                    exectAPI.CreateDocument(mainEntity, ref infoEntity);
                    if (infoEntity.OutFlag == 1)
                    {
                        NameAndRev.Add(m_StrDocumentName, "1");
                        Log.WriteOrcale("PDMTOMES_Product" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }
                    else if (infoEntity.OutFlag == 2)
                    {
                        Log.WriteOrcale("PDMTOMES_Product" + infoEntity.StrServicekey + "@^" + "Document创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                    }
                }
                info1Entity = new OutInfoEntity();
                exectAPI.CreateDocumentSet(DocumentSetName, NameAndRev, ref info1Entity);

                if (info1Entity.OutFlag == 1)
                {
                    m_StrDocumentName = DocumentSetName;
                    Log.WriteOrcale("PDMTOMES_Product" + info1Entity.StrServicekey + "@^" + info1Entity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
                else
                {
                    m_StrDocumentName = "";
                    Log.WriteOrcale("PDMTOMES_Product" + info1Entity.StrServicekey + "@^" + "DocumentSet创建失败:" + info1Entity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                }
            }
            catch { }
        }

        private void GetDocumentList(List<string> FilesNameList, TreeNode item)
        {
            foreach (TreeNode docNode in item.Nodes)
            {
                if (docNode.Text == "ProductDocuments")
                {
                    foreach (TreeNode fileNode in docNode.Nodes)
                    {
                        FilesNameList.Add(fileNode.Tag.ToString());
                    }
                }
                else
                {
                    GetDocumentList(FilesNameList, docNode);
                }
            }
        }

        public void ShowAttribute()
        {

        }

        /// <summary>
        /// 存储urls
        /// add:Wangjh 2018/11/14 
        /// </summary>
        private void LoadUrls()
        {
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            //获取件号url信息
            XmlNodeList urlNodes = myxml.SelectNodes("/Root/product/item/Urls/Url");
            if (urlNodes.Count == 0)
                return;
            StandardDAL dal = new StandardDAL();
            Dictionary<string, string> para = new Dictionary<string, string>();
            para["ParentID"] = dal.GetRDOID("product", "productname", strProductName, "productrevision", strVersion);
            if (string.IsNullOrWhiteSpace(para["ParentID"]))
                return;
            foreach (XmlNode url in urlNodes)
            {
                string name = "", link = "";
                foreach (XmlNode urlItem in url.ChildNodes)
                {
                    if (urlItem.Name == "name")
                        name = urlItem.InnerText;
                    if (urlItem.Name == "link")
                        link = urlItem.InnerText;
                    if (name != "" && link != "")
                    {
                        para["FileName"] = name;
                        para["Link"] = link;
                        dal.InsertUrl(para);
                    }
                }
            }

        }

        #region 附件重新处理 add:Wangjh 20211101
        private void LoadDocumentNew(List<string> FilesNameList)
        {
            try
            {
                StandardDAL dal = new StandardDAL();
                string DocumentSetName = "";
                if (FilesNameList.Count == 0)
                {

                    return;
                }
                string parentId = dal.GetRDOID("product", "productname", strProductName, "productrevision", strVersion);
                if (string.IsNullOrWhiteSpace(parentId))
                    return;
                //文档集名称
                DocumentSetName = string.Format("{0}-{1}-{2}", strProductName, strVersion, DateTime.Now.ToString("yyyyMMddHHmmssffff"));


                for (int k = 0; k < FilesNameList.Count; k++)
                {
                    if (!File.Exists(m_AccessoriesPath + "\\" + FilesNameList[k]))
                    {
                        Log.WriteLog("未找到文件", 0, FilesNameList[k] + "未找到,跳过处理！");
                        Log.WriteOrcale("PDMTOMES_ProductDocument" + "@^" + "未找到文件" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   
                        continue;
                    }
                    // m_StrDocumentName = string.Format("{0}-{1}", Path.GetFileNameWithoutExtension(FilesNameList[k]), DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                    string strAA = m_Assistant.uniqName();
                    string strTmp1 = m_camstarpathtemp + strAA;

                    if (!Directory.Exists(strTmp1))
                        Directory.CreateDirectory(strTmp1);

                    File.Move(m_AccessoriesPath + "\\" + FilesNameList[k], strTmp1 + "\\" + FilesNameList[k]);

                    dal.SaveObjectDocInfo(parentId, "Temp/" + strAA + @"/" + FilesNameList[k], FilesNameList[k]);

                    Log.WriteOrcale("PDMTOMES_Product" + "Document" + "@^" + FilesNameList[k] + " 附件保存成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + strProductName + ":" + strVersion);//add:Wangjh 写入数据库   

                }

            }
            catch { }
        }
        #endregion
    }
}